// Dart imports:

// Flutter imports:
import 'dart:io';

import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter/material.dart';

// Package imports:
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:location/location.dart' as mLocation;

// Project imports:
import 'widget/permission_confirm_dialog.dart';

class PermissionUtils {
  static checkCameraPermission({required Function onGrant}) async {
    var status = await Permission.camera.request();
    if (status.isGranted) {
      onGrant();
    } else {
      showDialog(
          context: Get.context!,
          builder: (ctx) {
            return buildConfirmDialog("authorizedCamera".tr);
          });
    }
  }

  static Future<bool> checkLocationPermission() async {
    var status = await Permission.locationWhenInUse.request();
    mLocation.Location location = mLocation.Location();
    bool _serviceEnabled;
    _serviceEnabled = await location.serviceEnabled();
    if (!_serviceEnabled) {
      _serviceEnabled = await location.requestService();
      if (!_serviceEnabled) {
        return false;
      }
    }
    if (status.isGranted) {
      return true;
    } else {
      showDialog(
          context: Get.context!,
          builder: (ctx) {
            return buildConfirmDialog("authorizedLocation".tr);
          });
      return false;
    }
  }

  ///请求读写手机存储权限
  ///请求读写手机存储权限
  static Future<bool> checkStoragePermission() async {
    PermissionStatus statuses = await Permission.storage.request();
    if (statuses == PermissionStatus.granted) {
      if (Platform.isAndroid) {
        DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
        AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
        if (androidInfo.version.sdkInt >= 31) {
          PermissionStatus manageExternalStorage =
              await Permission.manageExternalStorage.request();
          if (manageExternalStorage == PermissionStatus.granted) {
            return true;
          } else {
            return false;
          }
        } else {
          return true;
        }
      } else {
        return true;
      }
    } else {
      showDialog(
          context: Get.context!,
          builder: (ctx) {
            return buildConfirmDialog("authorizedStorage".tr);
          });
      return false;
    }
  }
}
